using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;

namespace IQIGame.Onigao.GamePlay
{
    public class UIPetEditName : UIBaseWindow
    {
        #region Template Generate,don't modify
        protected class UIB_UIPetEditName
        {
            #region ObjectBinding Generate
            public IQIGame.Onigao.Framework.ExButton btnCancel { protected set; get; }
            public IQIGame.Onigao.Framework.ExButton btnConfirm { protected set; get; }
            public IQIGame.Onigao.Framework.ExInputField inputName { protected set; get; }
            public UnityEngine.GameObject emptyTip { protected set; get; }
            public IQIGame.Onigao.Framework.ExText textErrorTip { protected set; get; }
            public virtual void InitBinding(ObjectBinding __binding)
            {
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExButton>("btnCancel", out var __tbv0);
                this.btnCancel = __tbv0;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExButton>("btnConfirm", out var __tbv1);
                this.btnConfirm = __tbv1;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExInputField>("inputName", out var __tbv2);
                this.inputName = __tbv2;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("emptyTip", out var __tbv3);
                this.emptyTip = __tbv3;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExText>("textErrorTip", out var __tbv4);
                this.textErrorTip = __tbv4;
            }
            #endregion ObjectBinding Generate 
        }
        #endregion Template Generate,don't modify

        #region Window Config
        /// <summary>
        /// 静态配置
        /// </summary>
        private static UICreateConfig _createConfig = new()
        {
            prefabName = nameof(UIPetEditName),
            layer = EUILayer.Normal,
        };

        /// <summary>
        /// 创建UI的配置
        /// </summary>
        public override IUICreateConfig createConfig => _createConfig;
        #endregion Window Config

        #region fields

        private Pet pet;
        private string oldName = null;

        #endregion fields

        #region properties

        protected UIB_UIPetEditName ui { get; set; }
        protected UIMsgDispatcher uiMsgDispatcher => this._msgDispatcher as UIMsgDispatcher;

        #endregion properties

        protected override void BeforeInit()
        {
            ui = new UIB_UIPetEditName();
            ui.InitBinding(this.csObjBind);
        }

        protected override void OnInit()
        {

        }

        protected override void OnShow(UIBaseData data)
        {
            this.SetData(data as UD_PetEditName);
            this.ShowView();
        }

        protected override void OnHide()
        {

        }

        /// <summary>
        /// 添加UGUI侦听
        /// </summary>
        protected override void AddUGUIListener()
        {
            this.ui.inputName.onEndEdit.AddListener(this.OnInputEnd);
            this.ui.btnConfirm.onClick.AddListener(this.OnClickConfirm);
            this.ui.btnCancel.onClick.AddListener(this.OnClickCancel);
        }

        /// <summary>
        /// 添加全局侦听（MsgDispatcher）
        /// </summary>
        protected override void AddMsgListeners()
        {

        }

        protected override void OnDispose()
        {

        }

        #region methonds

        private void SetData(UD_PetEditName data)
        {
            this.pet = data.pet;
            this.oldName = this.pet.GetName();
        }

        private void ShowView()
        {
            string name = this.pet.GetName();
            bool isEmpty = this.IsDefaultName(name);

            this.ShowName(name);
            this.ShowErrorTip("");
            this.SetActiveEmptyTip(isEmpty);
        }

        private bool IsDefaultName(string name)
        {
            return string.IsNullOrEmpty(name) || string.Equals(name, this.pet.cfgData.Name);
        }

        private void ShowName(string name)
        {
            this.ui.inputName.text = name;
        }

        private void ShowErrorTip(string tip)
        {
            this.ui.textErrorTip.text = tip;
        }

        private void SetActiveEmptyTip(bool active)
        {
            this.ui.emptyTip.SetActive(active);
        }

        private void OnInputEnd(string val)
        {
            bool isEmpty = string.IsNullOrEmpty(val);
            this.SetActiveEmptyTip(isEmpty);
            if (isEmpty)
            {
                this.ShowErrorTip("");
            }
        }

        private void OnClickConfirm()
        {
            string str = this.ui.inputName.text;
            if (string.Equals(this.oldName, str))
            {
                this.Close();
                return;
            }

            string limitStr = APIUIPet.GetStrLimitPetInputName(str);
            if (!string.IsNullOrEmpty(limitStr))
            {
                this.ShowErrorTip(limitStr);
                return;
            }
            this.SendChangePetName(str).Forget();
        }

        private async UniTaskVoid SendChangePetName(string petName)
        {
            var result = await PetModule.NetCore.CS_rename(this.pet.id, petName);
            if (result.IsSuccess)
            {
                this.pet.UpdateName(petName);
                MsgDispatcher.Broadcast(MsgEventType.PetRenameSuccess);
                this.Close();
            }
            else
            {
                var cfgOne = TableCenter.errorCode.Get(result.code);
                if (cfgOne != null)
                    this.ShowErrorTip(cfgOne.Describe);
            }
        }

        private void OnClickCancel()
        {
            this.Close();
        }
        #endregion methonds
    }
}
